import React, { useState } from 'react';
import { Modal, Form, Input, Select, Button, Space } from 'antd';
import { ProtocolFormValues } from '../../types/protocol';

interface ProtocolAddProps {
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: ProtocolFormValues) => void;
}

const { Option } = Select;
const { TextArea } = Input;

const ProtocolAdd: React.FC<ProtocolAddProps> = ({ visible, onCancel, onSubmit }) => {
  const [form] = Form.useForm();
  const [pollCommands, setPollCommands] = useState<string[]>([]);

  // 当模态框关闭时重置表单
  React.useEffect(() => {
    if (!visible) {
      form.resetFields();
      setPollCommands([]);
    }
  }, [visible, form]);

  // 协议类型选项
  const protocolTypes = [
    { value: 'MQTT', label: 'MQTT' },
    { value: 'HTTP', label: 'HTTP' },
    { value: 'CoAP', label: 'CoAP' },
    { value: 'Modbus', label: 'Modbus' },
    { value: 'OPC-UA', label: 'OPC-UA' },
    { value: 'Other', label: '其他' },
  ];

  // 校验帧尾选项
  const checkFrameTailOptions = [
    { value: 'CRC16', label: 'CRC16' },
    { value: 'Sum', label: '累加和' },
    { value: 'Custom', label: '自定义' },
    { value: 'None', label: '不校验' },
  ];

  // 处理添加轮询指令
  const handleAddPollCommand = () => {
    setPollCommands([...pollCommands, '']);
  };

  // 处理轮询指令输入变化
  const handlePollCommandChange = (index: number, value: string) => {
    const newCommands = [...pollCommands];
    newCommands[index] = value;
    setPollCommands(newCommands);
  };

  // 处理删除轮询指令
  const handleRemovePollCommand = (index: number) => {
    const newCommands = pollCommands.filter((_, i) => i !== index);
    setPollCommands(newCommands);
  };

  // 处理表单提交
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        // 合并轮询指令
        const formValues: ProtocolFormValues = {
          ...values,
          pollCommands: pollCommands.filter(cmd => cmd.trim() !== ''),
        };
        onSubmit(formValues);
      })
      .catch(info => {
        console.log('表单验证失败:', info);
      });
  };

  return (
    <Modal
      title="添加协议"
      open={visible}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={handleSubmit}>
          确认添加
        </Button>,
      ]}
      width={800}
    >
      <Form
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        initialValues={{
          type: 'MQTT',
          checkFrameTail: 'CRC16',
        }}
      >
        <Form.Item
          name="name"
          label="协议名称"
          rules={[
            { required: true, message: '请输入协议名称' },
            { max: 50, message: '协议名称不能超过50个字符' },
          ]}
        >
          <Input placeholder="请输入协议名称" />
        </Form.Item>

        <Form.Item
          name="type"
          label="协议类型"
          rules={[
            { required: true, message: '请选择协议类型' },
          ]}
        >
          <Select placeholder="请选择协议类型">
            {protocolTypes.map(type => (
              <Option key={type.value} value={type.value}>{type.label}</Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="description"
          label="协议描述"
          rules={[
            { max: 200, message: '协议描述不能超过200个字符' },
          ]}
        >
          <TextArea rows={3} placeholder="请输入协议描述" />
        </Form.Item>

        <Form.Item
          name="frameHeader"
          label="帧头"
          rules={[
            { required: true, message: '请输入帧头' },
          ]}
        >
          <Input placeholder="请输入帧头" />
        </Form.Item>

        <Form.Item
          name="frameLength"
          label="帧长度"
          rules={[
            { required: true, message: '请输入帧长度' },
          ]}
        >
          <Input placeholder="请输入帧长度" />
        </Form.Item>

        <Form.Item
          name="checkStart"
          label="校验起始位"
          rules={[
            { required: true, message: '请输入校验起始位' },
          ]}
        >
          <Input placeholder="请输入校验起始位" />
        </Form.Item>

        <Form.Item
          name="checkEnd"
          label="校验结束"
          rules={[
            { required: true, message: '请输入校验结束' },
          ]}
        >
          <Input placeholder="请输入校验结束" />
        </Form.Item>

        <Form.Item
          name="checkFrameTail"
          label="校验帧尾"
          rules={[
            { required: true, message: '请选择校验帧尾' },
          ]}
        >
          <Select placeholder="请选择校验帧尾">
            {checkFrameTailOptions.map(option => (
              <Option key={option.value} value={option.value}>{option.label}</Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="自定义校验"
          dependencies={['checkFrameTail']}
          shouldUpdate={(prev: any, curr: any) => prev.checkFrameTail !== curr.checkFrameTail}
          noStyle
        >
          {({ getFieldValue }) => {
            const checkFrameTail = getFieldValue('checkFrameTail');
            return checkFrameTail === 'Custom' ? (
              <Form.Item
                name="customCheck"
                rules={[{
                  required: checkFrameTail === 'Custom',
                  message: '请输入自定义校验'
                }]}
              >
                <Input placeholder="请输入自定义校验" />
              </Form.Item>
            ) : null;
          }}
        </Form.Item>

        <Form.Item label="轮询指令" style={{ marginBottom: 0 }}>
          <div style={{ marginBottom: 10 }}>
            <Button type="dashed" onClick={handleAddPollCommand}>增加</Button>
          </div>
          <div>
            {pollCommands.map((cmd, index) => (
              <Space key={index} style={{ marginBottom: 8 }}>
                <Input
                  placeholder={`轮询指令 ${index + 1}`}
                  value={cmd}
                  onChange={e => handlePollCommandChange(index, e.target.value)}
                  style={{ width: 'calc(100% - 70px)' }}
                />
                <Button type="text" danger onClick={() => handleRemovePollCommand(index)}>删除</Button>
              </Space>
            ))}
          </div>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ProtocolAdd;